#include "mqttControl.h"

// const char* mqtt_server = "121.40.129.119";
const char* mqtt_server = "120.26.64.89";
const int mqtt_port = 1883;
// const char* mqtt_username = "xf";
const char* mqtt_username = "zg";
const char* mqtt_password = "12345678";
const char* mqtt_clientId = "ESP32Client-cocoaxf";
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE	(50)
char msg[MSG_BUFFER_SIZE];
int value = 0;

//回调函数，当收到订阅的时候会调这个函数
void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  char* str = (char*)malloc(length + 1); 
  str[0] = '\0'; // 初始化为空字符串
  for (int i = 0; i < length; i++) {
    size_t len = strlen(str);
    str[len] = (char)payload[i];
    str[len + 1] = '\0';
   // Serial.println((char)payload[i]);
  }
  Serial.println(str);
  free(str);

}
//重新链接mqtt
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    
    // Attempt to connect
    if (client.connect(mqtt_clientId,mqtt_username,mqtt_password)) {
      Serial.println("connected");
      // ... and resubscribe
      client.subscribe("xufei");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
void mqttControl_init(void){

    client.setServer(mqtt_server, mqtt_port);//
    client.setCallback(callback);//设置mqtt回调函数

}
void mqtt_Push(const char* topic,const char* payload){

    client.publish(topic,payload);
}

void mqtt_loop(void){

    if (!client.connected()) {
    reconnect();
  }
  client.loop();//1.保持心跳 2.如果收到消息底层调用callback函数 3.处理mqtt消息队列
  // client.publish("cocoaxf","hello");
  // delay(5000);
}